package com.tevintao.marketingsystem.tool;

import com.tevintao.marketingsystem.log.LogManager;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * Created by tevintao on 2016/3/12.
 */
public class GetUrlContent {
    public static String getWebCon(String domain) {
        // System.out.println("开始读取内容...("+domain+")");
        StringBuffer sb = new StringBuffer();
        try {
            java.net.URL url = new java.net.URL(domain);
            BufferedReader in = new BufferedReader(new InputStreamReader(url
                    .openStream()));
            String line;
            while ((line = in.readLine()) != null) {
                sb.append(line);
            }
            System.out.println(sb.toString());
            in.close();
        } catch (Exception e) { // Report any errors that arise
            sb.append(e.toString());
            System.err.println(e);
            System.err.println("Usage:   java   HttpClient   <URL>   [<filename>]");
        }
        return sb.toString();
    }


    public static String getcontent(String url) {
        StringBuffer temp = new StringBuffer();
        try {
            HttpURLConnection uc = (HttpURLConnection) new URL(url).openConnection();
            uc.setConnectTimeout(10000);
            uc.setRequestMethod("GET");
            uc.setUseCaches(false);

            InputStream in = new BufferedInputStream(uc.getInputStream());
            Reader rd = new InputStreamReader(in, "utf-8");
            int c = 0;
            while ((c = rd.read()) != -1) {
                temp.append((char) c);
            }
            in.close();

            String buf = temp.toString();
            int beginIx = buf.indexOf("当前 IP");
            int endIx = buf.indexOf("来自");
            String result = buf.substring(beginIx, endIx);
            LogManager.getInstance().logInfo("当前IP地址 " + result);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return temp.toString();
    }
}
